package com.lambkit.module.common;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.template.source.ISource;
import com.jfinal.template.source.ISourceFactory;
import com.lambkit.core.Lambkit;
import com.lambkit.db.sql.Example;
import com.lambkit.module.common.row.PageTemplate;
import com.lambkit.module.common.service.PageTemplateService;
import com.lambkit.module.common.sql.PageTemplateSQL;
import com.lambkit.util.Printer;

/**
 * @author yangyong(孤竹行)
 */
public class DbSourceFactory implements ISourceFactory {
    @Override
    public ISource getSource(String baseTemplatePath, String fileName, String encoding) {
        String webRootPath = Lambkit.context().resourceService().getWebRootPath();
        webRootPath = webRootPath.replace("\\", "/");
        Printer.print(this, "starter", "DbSourceFactory webRootPath:" + webRootPath);
        if(baseTemplatePath.startsWith(webRootPath)) {
            baseTemplatePath = baseTemplatePath.substring(webRootPath.length());
        }
        Printer.print(this, "starter", "DbSourceFactory fileName:" + fileName);
        Printer.print(this, "starter", "DbSourceFactory baseTemplatePath:" + baseTemplatePath);
        baseTemplatePath = baseTemplatePath.replace("\\", "/");
        baseTemplatePath += fileName;
        baseTemplatePath = baseTemplatePath.substring(0, baseTemplatePath.lastIndexOf("/"));
        Printer.print(this, "starter", "DbSourceFactory catalog:" + baseTemplatePath);
        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        Printer.print(this, "starter", "DbSourceFactory name:" + fileName);
        PageTemplateService service = Lambkit.get(PageTemplateService.class);
        String catalog = baseTemplatePath;
        if(StrUtil.isBlank(catalog)) {
            catalog = "/";
        }
        Example example = PageTemplateSQL.of().andNameEqualTo(fileName).andCatalogEqualTo(catalog).example();
        PageTemplate templateModel = service.dao().findFirst(example);
        if(templateModel!=null) {
            Printer.print(this, "starter", "DbSourceFactory templateModel:" + JSON.toJSON(templateModel));
        }
        return new DbSource(templateModel, encoding);
    }
}
